<template>
  <a-modal
    v-model:visible="visible"
    :destroy-on-close="true"
    centered
    title="选择表单"
    width="100%"
    :confirm-loading="confirmLoading"
    :mask-closable="false"
    :keyboard="false"
    wrap-class-name="tn-model-full-scroll full-scroll-1200"
  >
    <template #footer>
      <a-button key="back" @click="visible = false">取消</a-button>
      <a-button key="submit" type="primary" ghost :loading="confirmLoading" @click="handleOk(true)">
        使用空白模板
      </a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" @click="handleOk(false)">确定</a-button>
    </template>
    <a-layout class="select_template_layout">
      <a-layout-header v-if="hasSearch" class="select_template_search">
        <a-form :model="form" layout="inline" :label-width="100">
          <a-form-item>
            <a-select
              v-model:value="form.projectType"
              :style="{ width: '200px' }"
              placeholder="试验类型"
              allow-clear
              class="gray"
              @change="getFormTemplateList"
            >
              <a-select-option v-for="(item, index) in experimentTypeOptions" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item v-if="isConfig() && !appId">
            <a-select
              v-model:value="form.appId"
              :get-popup-container="
                (triggerNode) => {
                  return triggerNode.parentNode
                }
              "
              placeholder="适用应用"
              style="min-width: 200px"
              allow-clear
              class="gray"
              @change="changeAppId"
            >
              <a-select-option v-for="(item, index) in appIdList" :key="index" :value="item.appId">
                {{ item.appName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-select
              v-model:value="form.formType"
              allow-clear
              :get-popup-container="
                (triggerNode) => {
                  return triggerNode.parentNode
                }
              "
              placeholder="表单类型"
              style="min-width: 200px"
              class="gray"
              @change="getFormTemplateList"
            >
              <a-select-option v-for="(item, index) in formTypeList" :key="index" :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <TnSearchInput
              v-model:value="form.formName"
              placeholder="按表单名称模糊搜索"
              @search="getFormTemplateList"
            />
          </a-form-item>
        </a-form>
      </a-layout-header>
      <a-layout v-if="ProgressTemplateList.length">
        <a-layout-sider :width="240" class="select_template_sider">
          <a-card class="full-card" :body-style="{ padding: 0, overflow: 'auto' }" :bordered="false" title="表单名称">
            <div class="show_list_ul">
              <div
                v-for="item in ProgressTemplateList"
                :key="item.formId"
                :class="['show_list_li', activeKey === item.formId ? 'active' : '']"
                @click="activeKey = item.formId"
              >
                <customShowTooltips :max-width="200" :content="item.formName"></customShowTooltips>
              </div>
            </div>
          </a-card>
        </a-layout-sider>
        <a-layout-content class="select_template_content">
          <DynamicFormRender :form-id="activeKey" :form-business-level="props.templateType" />
        </a-layout-content>
      </a-layout>
      <IcpEmpty v-if="!ProgressTemplateList.length"></IcpEmpty>
    </a-layout>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { formlist, formSelect, formBlankAdd, formSelectApp } from '@@/api/form'
import { experimentTypeOptions } from '@@/components/logicflow/index'
// import DynamicFormRender from '@/components/DynamicModule/DynamicFormRender/index.vue'
import { isConfig } from '@@/utils/index'
import { appLoadList } from '@@/api/common'
import { getDictdata } from '@@/api/portal/dictdata'

const props = defineProps<{
  taskId?: string | undefined
  entryType?: number | string | undefined
  formBusinessLevel: number
  templateType?: number
  hasSearch?: boolean
  appId?: string // 特殊入口处理appId
}>()

const emits = defineEmits(['submit', 'showEmpty'])

const visible = ref(false)
const ProgressTemplateList = ref<any>([])
const activeKey = ref('')
const confirmLoading = ref<boolean>(false)
const form = ref({
  formType: undefined,
  projectType: undefined,
  formName: undefined,
  appId: undefined
})

const show = () => {
  visible.value = true
  form.value = {
    formType: undefined,
    projectType: undefined,
    formName: undefined,
    appId: undefined
  }
  getFormTemplateList()
  getAppIdList()
}

const getFormTemplateList = () => {
  const params = Object.assign(
    {
      formBusinessLevel: props.templateType,
      belongBusinessId: 0,
      formType: undefined,
      formClass: 1,
      projectType: undefined,
      formName: undefined,
      formStatus: 1,
      pageNum: 1,
      pageSize: 100
    },
    form.value,
    {
      // 药房的业务配置里面只引用适用适用为药房管理的
      appId: props.appId || form.value.appId
    }
  )
  formlist(params).then((res) => {
    const data: any = res || []
    ProgressTemplateList.value = data.list
    activeKey.value = ProgressTemplateList.value[0]?.formId
  })
}

/**
 * @description: 选择审批流程
 * @param {isEmpty} 是否使用空白模板 true 是 false 否
 */
const handleOk = (isEmpty) => {
  confirmLoading.value = true
  let fn: any = null
  if (isEmpty) {
    if (props.formBusinessLevel === 2) {
      fn = formBlankAdd
    } else {
      confirmLoading.value = false
      emits('showEmpty')
      visible.value = false
      return
    }
  } else if (props.formBusinessLevel === 4) {
    fn = formSelectApp
  } else {
    fn = formSelect
  }
  fn({
    sourceFormId: activeKey.value,
    formBusinessLevel: props.formBusinessLevel,
    belongBusinessId: props.taskId,
    belongDomainId: props.formBusinessLevel === 4 ? sessionStorage.getItem('__projectId') : null
  })
    .then(() => {
      confirmLoading.value = false
      emits('submit', true)
      visible.value = false
    })
    .catch(() => {
      confirmLoading.value = false
    })
}
const changeAppId = () => {
  form.value.formType = undefined
  getFormTypeList()
  getFormTemplateList()
}
const appIdList = ref()
const getAppIdList = () => {
  appLoadList({
    pageSize: 100,
    pageNum: 1
  }).then((res) => {
    appIdList.value = res.list
    getFormTypeList()
  })
}
const formTypeList = ref<any>([])
const getFormTypeList = () => {
  let flag = window.location.href.includes('/pharmacy/') ? 'Pharmacy' : 'CTMS'
  if (isConfig()) {
    // 运维端
    const _appId = form.value.appId || props.appId
    if (!_appId) {
      formTypeList.value = []
      return
    }
    flag = appIdList.value.find((item) => item.appId === _appId)?.appCode
  }
  getDictdata({
    appCode: 'CTMS-OPERATION',
    flag
  }).then((res) => {
    formTypeList.value = res[flag] || []
  })
}

defineExpose({
  show
})
</script>
